package com.chen.authority.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.authority.common.constant.SysConstant;
import com.chen.authority.common.model.PageQo;
import com.chen.authority.common.response.Response;
import com.chen.authority.common.util.WrapperUtil;
import com.chen.authority.mapper.PostMapper;
import com.chen.authority.mapper.UserMapper;
import com.chen.authority.model.dto.PostDto;
import com.chen.authority.model.po.PostPo;
import com.chen.authority.model.po.UserPo;
import com.chen.authority.model.qo.PostQo;
import com.chen.authority.model.vo.PostVo;
import com.chen.authority.service.PostService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * 岗位信息Service业务层处理
 *
 * @author chengy
 * @date 2022-08-19
 */
@Service
@RequiredArgsConstructor
public class PostServiceImpl extends ServiceImpl<PostMapper, PostPo> implements PostService {

    private final UserMapper userMapper;

    @Override
    public Response addOrUpdatePost(Integer id, PostDto dto) {
        boolean notNull = ObjectUtil.isNotNull(id);

        boolean exists = baseMapper.exists(Wrappers
                .<PostPo>lambdaQuery()
                .and(sql -> sql
                        .eq(PostPo::getName, dto.getName())
                        .or()
                        .eq(PostPo::getCode, dto.getCode()))
                .ne(notNull, PostPo::getId, id));
        if (exists) return Response.fail("岗位名称或编码重复，请检查");

        PostPo post = dto.toPo(PostPo.class);

        if (notNull) {
            if (dto.getStatus() == SysConstant.DISABLE && checkPostIsUse(id)) {
                return Response.fail("该岗位下存在员工，无法禁用");
            }
            post.setId(id);
        }

        return this.saveOrUpdate(post) ? Response.success() : Response.fail();
    }

    @Override
    public Response deletePostByIds(Integer[] ids) {
        if (checkPostIsUse(ids)) return Response.fail("存在岗位与员工挂职，无法删除");
        return this.removeByIds(Arrays.asList(ids)) ? Response.success() : Response.fail();
    }

    @Override
    public Page<PostVo> pageQueryPostList(PageQo pageQo, PostQo postQo) {
        return baseMapper.selectVoPage(pageQo.build(), WrapperUtil.buildQueryWrapper(postQo));
    }

    @Override
    public List<PostVo> exportPostList(QueryWrapper<PostPo> queryWrapper) {
        return baseMapper.selectVoList(queryWrapper);
    }

    private boolean checkPostIsUse(Integer... ids) {
        return userMapper.exists(Wrappers.<UserPo>lambdaQuery().in(UserPo::getPostId, ids));
    }

}